package com.zz.yt.lib.login.delegate.login;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.zz.yt.lib.login.R;
import com.zz.yt.lib.login.constant.ILoginListener;
import com.zz.yt.lib.login.delegate.login.base.BaseSigInDelegate;
import com.zz.yt.lib.login.view.ButtonCloudView;


/**
 * 多平台切换登录
 *
 * @author qf
 * @version 2023-1-03
 */
public class SignInCloudDelegate extends BaseSigInDelegate {

    private ButtonCloudView cloudView;
    private ILoginListener mLoginListener = null;


    @Override
    public void onAttach(@NonNull Context activity) {
        super.onAttach(activity);
        //这里是类型转换，而不是判断
        if (activity instanceof ILoginListener) {
            mLoginListener = (ILoginListener) activity;
        }
    }

    @Override
    public Object setLayout() {
        return R.layout.hai_delegate_sign_in_cloud;
    }

    private void inBundle() {
        if (mLoginListener != null) {
            Object launcher = mLoginListener.setSignIn();
            if (launcher != null) {
                if (launcher instanceof Integer) {
                    getImageView(R.id.id_image_background)
                            .setImageResource((int) launcher);
                } else if (launcher instanceof View) {
                    RelativeLayout view = findViewById(R.id.id_layout_background);
                    view.addView((View) launcher);
                }
            }
        }
        //设置是否保存登录信息
        setSelect(true);

        cloudView = findViewById(R.id.id_button_cloud_view);
        if (cloudView != null) {
            cloudView.onCloud(getAccount(), getPassword());
        }
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        inBundle();
        inGradePermission();
    }

    @Override
    protected void onGrantedSuccess() {
        if (cloudView != null) {
            cloudView.setOnCloudListener((account, password) -> {
                if (isGranted()) {
                    setInstallPermission();
                    return;
                }
                if (isAccount(account) && isPassword(password)) {
                    mLoginListener.onSignIn(account, password);
                }
            });
        }
    }


}